package com.lagou.homework04;

import java.util.Date;

public class TicketRunnableTest implements Runnable {
    private int balance; // 描述车票数量
    private  Date d1 = new Date();
    public TicketRunnableTest() {
    }

    public TicketRunnableTest(int balance) {
        setBalance(balance);
    }

    public int getBalance() {
        return balance;
    }
    public void setBalance(int balance) {
        this.balance = balance;

    }
    @Override
    public void run() {
        synchronized (d1) {// 注意事项，调用run()的是balance，是唯一一把锁
            int b1 = getBalance(); // 模拟从后台查询火车票余额
            if(b1 > 0 && b1 <= 100) {
                System.out.println("正在出票......");
                b1--;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("请拿好票");
            } else {
                System.out.println("火车票的数量不合理！");
            }
            setBalance(b1);
        }
    }

    public static void main(String[] args) {

        TicketRunnableTest trt = new TicketRunnableTest(100);
        Thread t1 = new Thread(trt);
        Thread t2 = new Thread(trt);
        Thread t3 = new Thread(trt);
        t1.start();
        t2.start();
        t3.start();
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("火车票剩余数量：" + trt.getBalance());
    }
}
